package cn.scut.srp.aop;

import cn.scut.srp.utils.JWTUtils;
import cn.scut.srp.utils.ResponseUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Aspect
@Component
@Slf4j
public class LoginInterceptor {

    @Autowired
    private JWTUtils jwt;

    @Around("execution(* cn.scut.srp.controller.afterLogin.*.*.*(..))")
    @Order(1)
    public Object doLoginInterceptor(ProceedingJoinPoint point) throws Throwable{
        String token = (String) point.getArgs()[0];
        if (token == null) {
            log.info("用户没登录");
            return ResponseUtil.notLogin("请先登录");
        }

        HashMap<String, Object> map = null;
        try {
            map = jwt.analyzeToken(token);
        } catch (ExpiredJwtException e) {
            return ResponseUtil.loginExpired("登录已超时,请重新登录");
        }
        Long expireTime = (Long) map.get("expireTime");
        if (expireTime <= System.currentTimeMillis()) {
            //没过期,可以放行了
            return point.proceed();
        }

        log.info("user {} 登陆超时", map.get("userID"));
        return ResponseUtil.loginExpired("登录已超时,请重新登录");
    }
}
